//
//  ViewController.swift
//  C006_test_custom_table
//
//  Created by yao_yu on 15/5/25.
//  Copyright (c) 2015年 yao_yu. All rights reserved.
//

import UIKit


class GchfTreeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableView = UITableView()
    var rows: [NSDictionary]?
    var nodes: [String: YYTreeNode]!
    var lastIndexPath: NSIndexPath!
    var lastPoint: CGPoint!
    var lastN = 0
    var lastItemIndex: Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        tableView.delegate = self
        tableView.dataSource = self
        //tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
        view.addSubview(tableView)
        
//        var panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
//        tableView.addGestureRecognizer(panGestureRecognizer)
        let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handlePan:")
        tableView.addGestureRecognizer(gestureRecognizer)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
        tableView.addGestureRecognizer(tapGesture)
        
        loadData()
    }
    
    
    func handleTap(recognizer: UIGestureRecognizer)
    {
        let tapPoint:CGPoint = recognizer.locationInView(tableView)
        if let indexPath = tableView.indexPathForRowAtPoint(tapPoint) {
            let row = rows![indexPath.row]
            let parentId = row["pbh"] as! String
            let n =  tapPoint.x < 250 ? -1 : 1
            if let parentNode = nodes[parentId],
                index = parentNode.findChildIndex(row["gcbh"] as! String) ,
                node = parentNode[index + n],
                    nindex = rows!.indexOf(node.data)
                {
                    let scrollIndexPath = NSIndexPath(forRow: nindex, inSection: 0)
                    tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
                }
            
        }
    
    }


    func handlePan(recognizer: UIGestureRecognizer)
    {
        let translation:CGPoint =  recognizer.locationInView(self.view)
        let indexPath = tableView.indexPathForRowAtPoint(recognizer.locationInView(tableView))

        switch recognizer.state {
        case UIGestureRecognizerState.Began:
            lastPoint = translation
            lastIndexPath = indexPath
            lastN = 0
            lastItemIndex = nil
            if lastIndexPath != nil {
                let row = rows![lastIndexPath.row]
                let parentId = row["pbh"] as! String
                if let parentNode = nodes[parentId], index = parentNode.findChildIndex(row["gcbh"] as! String){
                    lastItemIndex = index
                }
            }
        case UIGestureRecognizerState.Changed:
            let deltaY = translation.y - lastPoint.y
            let n = -Int(deltaY / 44)
            if n != lastN {
                lastN = n
                if lastIndexPath != nil && lastItemIndex != nil {
                    print(lastItemIndex + lastN)
                    let row = rows![lastIndexPath.row]
                    if let parentNode = nodes[row["pbh"] as! String],
                        node = parentNode[lastItemIndex + lastN],
                        index = rows!.indexOf(node.data)
                    {
                        let scrollIndexPath = NSIndexPath(forRow: index, inSection: 0)
                        tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
                    }
                }
            }
            
        case UIGestureRecognizerState.Ended:
            lastPoint = nil
            lastIndexPath = nil
            lastN = 0
        default:
            ""
        }


    
    }
    
    func loadData(){
        let data = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("gclist", ofType: ".json")!)
        var jsonObject:NSDictionary?
        do {
            jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
        } catch {

        }

        rows = jsonObject?["rows"] as? [NSDictionary]
        rows?.sortInPlace({ (a:NSDictionary, b:NSDictionary) -> Bool in
            if (a["cj"] as! Int) < (b["cj"] as! Int) {
                return true
            }
            return Int(a["pxh"] as! String)! < Int(b["pxh"] as! String)!
        })
        sortRows()
    }
    
    func sortRows() {
        
        let rootNode = YYTreeNode(id: "", data: NSDictionary())
        nodes = [rootNode.id: rootNode]
        for row in rows! {
            if let parentNode = nodes[row["pbh"] as! String] {
                let node = YYTreeNode(id: row["gcbh"] as! String, data:row)
                nodes[node.id] = node
                parentNode.append(node)
            } else {
                print("未知父节点,\(row)")
            }
        }
//        nodes.removeAll(keepCapacity: false)
//        var index = -1
        rows = rootNode.getDatas(true)
        
    }
    
    override func viewDidLayoutSubviews() {
        tableView.frame = CGRectMake(0, 20, view.frame.width, view.frame.height - 20)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let _rows = rows {
            return _rows.count
        }
        return 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        }
        
        let row = rows?[indexPath.row]
        

        cell?.detailTextLabel?.text = row?["gcbh"] as? String
        cell?.textLabel?.text = row?["gcmc"] as? String
        
        let cj:Int = row?["cj"] as! Int
        
        cell?.indentationLevel = cj - 1
        cell?.indentationWidth = 20
//        cell?.indentationWidth = CGFloat(cj * 40)
        
        return cell!
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

